package com.jingdianjichi.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.nacos.common.utils.StringUtils;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.jingdianjichi.gateway.entity.AuthPermission;
import com.jingdianjichi.gateway.entity.AuthRole;
import com.jingdianjichi.gateway.redis.RedisUtil;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展 
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private RedisUtil redisUtil;
    private String authPermissionPrefix="auth.permission";
    private String authRolePrefix="auth.role";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        //1.跟数据库交互
        //2.将权限和角色放到redis缓存
        //3.先从redis缓存中获取，没有的话在调用其他微服务去获取

        return getAuth(loginId,authPermissionPrefix);

    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表

        return getAuth(loginId,authRolePrefix);
    }
    private List<String> getAuth(Object loginId,String authPrefix){
        String authKey = redisUtil.buildKey(authPrefix, loginId.toString());
        String authValue = redisUtil.get(authKey);
        if (StringUtils.isBlank(authValue)) {
            return Collections.emptyList();

        }
        List<String> authList=new LinkedList<>();
        if(authRolePrefix.equals(authPrefix)){
            List<AuthRole> roleList=new Gson().fromJson(authValue,new TypeToken<List<AuthRole>>(){
            }.getType());
            authList=roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
        }else if(authPermissionPrefix.equals(authPrefix)){
            List<AuthPermission> permissionList=new Gson().fromJson(authValue,new TypeToken<List<AuthPermission>>(){
            }.getType());
            authList=permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        }
        return  authList;
    }

}
